/*
 * @Author: ljkt
 * @Version: 2.0
 * @Date: 2022-05-16 11:06:33
 * @LastEditors: ljkt
 * @LastEditTime: 2025-04-26 13:54:30
 * @Description:
 */
#include "Hal_Common_Func.h"
#if defined(EN_PWM0) || defined(EN_PWM1) || defined(EN_PWM2)
void Hal_Pwmx_Duty(s_hal_pwmx_config_t *config, unsigned short f, unsigned char duty)
{
	unsigned long Ram duty_cnt = 0X00;
	unsigned long Ram f_cnt = ((24 * 1000000) / (f));
	switch (config->chx)
	{
#ifdef EN_PWM0
	case e_HAL_PWM0:
		duty_cnt = duty;
		duty_cnt = duty_cnt * f_cnt / 100ul;
		PWM0_CH0_CNT_L = (uchar)duty_cnt;
		PWM0_CH0_CNT_H = (uchar)(duty_cnt >> 8);
		PWM0_MOD_L = (uchar)f_cnt;
		PWM0_MOD_H = (uchar)(f_cnt >> 8);
		break;
#endif
#ifdef EN_PWM1
	case e_HAL_PWM1:
		duty_cnt = duty;
		duty_cnt = duty_cnt * f_cnt / 100ul;
		PWM1_CH0_CNT_L = (uchar)(duty_cnt);
		PWM1_CH0_CNT_H = (uchar)(duty_cnt >> 8);
		PWM1_MOD_L = (uchar)f_cnt;
		PWM1_MOD_H = (uchar)(f_cnt >> 8);
		break;
#endif
#ifdef EN_PWM2
	case e_HAL_PWM2:
		duty_cnt = duty;
		duty_cnt = duty_cnt * f_cnt / 100ul;
		PWM2_CH0_CNT_L = (uchar)(duty_cnt);
		PWM2_CH0_CNT_H = (uchar)(duty_cnt >> 8);
		PWM2_MOD_L = (uchar)(f_cnt);
		PWM2_MOD_H = (uchar)(f_cnt >> 8);
		break;
#endif
	default:
		break;
	}
}

void Hal_Pwmx_Init(s_hal_pwmx_config_t *config)
{
	Hal_Gpio_Out(&config->gpio, config->level);
	Hal_Pwmx_Duty(config, config->freq, 0);
	switch (config->chx)
	{
#ifdef EN_PWM0
	case e_HAL_PWM0: // PWM0_A1-PB5
		TRISB &= ~0x20;
		REG_ADDR = 0x2D;
		REG_DATA |= 0x01;

		PWM0_CH_CTRL |= PWM0_CH_EN;
		PWM0_CH_CTRL |= (PWM0_POLO_SEL << 4);
		PWM_EN |= (PWM0_DUTY_MODE << 3);
		PWM_EN |= 0x01;
		PWM0_CH0_CNT_L = 0x00;
		PWM0_CH0_CNT_H = 0x00;
		PWM0_CH1_CNT_L = 0x00;
		PWM0_CH1_CNT_H = 0x00;
		PWM0_CH2_CNT_L = 0x00;
		PWM0_CH2_CNT_H = 0x00;
		PWM0_CH3_CNT_L = 0x00;
		PWM0_CH3_CNT_H = 0x00;
		PWM0_MOD_L = 0x00;
		PWM0_MOD_H = 0x00;
		break;
#endif
#ifdef EN_PWM1
	case e_HAL_PWM1:
		PWMX_CH_CTRL |= PWM1_CH_EN;
		PWMX_CH_CTRL |= (PWM1_POLO_SEL << 2);
		PWM_EN |= (PWM1_DUTY_MODE << 6);
		PWM_EN |= 0x02;
		PWM1_CH0_CNT_L = 0x00;
		PWM1_CH0_CNT_H = 0x00;
		PWM1_CH1_CNT_L = 0x00;
		PWM1_CH1_CNT_H = 0x00;
		PWM1_MOD_L = 0x00;
		PWM1_MOD_H = 0x00;
		break;
#endif
#ifdef EN_PWM2
	case e_HAL_PWM2:
		PWMX_CH_CTRL |= (PWM2_CH_EN << 4);
		PWMX_CH_CTRL |= (PWM2_POLO_SEL << 6);
		PWM_EN |= (PWM2_DUTY_MODE << 7);
		PWM_EN |= 0x04;
		PWM2_CH0_CNT_L = 0x00;
		PWM2_CH0_CNT_H = 0x00;
		PWM2_CH1_CNT_L = 0x00;
		PWM2_CH1_CNT_H = 0x00;
		PWM2_MOD_L = 0x00;
		PWM2_MOD_H = 0x00;

		break;
#endif
	default:
		break;
	}
}
void Hal_Pwmx_IF_Clr(s_hal_pwmx_config_t *config)
{
	switch (config->chx)
	{
#ifdef EN_PWM0
	case e_HAL_PWM0:
		break;
#endif
#ifdef EN_PWM1
	case e_HAL_PWM1:
		break;
#endif
#ifdef EN_PWM2
	case e_HAL_PWM2:
		break;
#endif
	default:
		break;
	}
}
#endif